package cn.wuwenyao.db.doc.generator.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import cn.wuwenyao.db.doc.generator.dao.DbInfoDao;
import cn.wuwenyao.db.doc.generator.dao.impl.MysqlDbInfoDao.TableFieldInfoRowMapper;
import cn.wuwenyao.db.doc.generator.dao.impl.MysqlDbInfoDao.TableInfoRowMapper;
import cn.wuwenyao.db.doc.generator.entity.TableFieldInfo;
import cn.wuwenyao.db.doc.generator.entity.TableInfo;

/** 
* @author  作者  xc E-mail: 
* @date 创建时间：2018年1月24日 上午10:30:15 
* @version 1.0 
* @parameter  
* @since  
* @return  
* 
* 获取oracle数据库信息
*/
 
@ConditionalOnProperty(name = "application.db.type", havingValue = "oracle")
@Component
public class OracleDbInfoDao implements DbInfoDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Value("${spring.datasource.username}")
	private String username;
	
	@Override
	public String databaseName() {
		 
		return username;
	}

	@Override
	public List<TableInfo> tableInfoList() {
		List<TableInfo> tableInfos = jdbcTemplate.query(
				"select t.table_name,c.comments table_comment from user_tables t ,user_tab_comments c where t.table_name = c.table_name",
				new TableInfoRowMapper());
		
		tableInfos.stream().forEach((tableInfo) -> {
			Object[] params = new Object[] { tableInfo.getTableName() ,tableInfo.getTableName()};
			List<TableFieldInfo> fields = jdbcTemplate.query(
					" select z.*, "+
					 " (select constraint_type"+
				             "    from user_cons_columns a, user_constraints b"+
				             "   where a.constraint_name = b.constraint_name"+
				              "    and b.constraint_type = 'P'"+
				             "     and a.table_name = ?"+
				              "    and a.column_name = z.column_name) COLUMN_KEY from "+
					"  ( select t4.column_name,"+
              " t1.comments COLUMN_COMMENT,"+
             "  data_default COLUMN_DEFAULT,"+
             "  nullable IS_NULLABLE,"+
             "  data_type || '(' || data_length || ')' COLUMN_TYPE, data_type,data_length,"+
             " '' as EXTRA from user_col_comments t1, user_tab_columns t4"+
              " where t1.column_name = t4.column_name"+
                "  and t4.table_name = ?"+
                 " and t1.table_name = t4.table_name)z",
					params, new TableFieldInfoRowMapper());
			tableInfo.setFields(fields);
		});
		return tableInfos;
		 
	}
	 
}
